// logger/logger.go
// package logger

// import (
//     "github.com/gin-gonic/gin"
//     "gopkg.in/natefinch/lumberjack.v2"
//     "io"
//     "log"
//     "os"
// )

// func SetupLogger() {
//     logFile := &lumberjack.Logger{
//         Filename:   "logs/diting.log",
//         MaxSize:    10,    // MB
//         MaxBackups: 5,
//         MaxAge:     30,    // days
//         Compress:   true,
//     }

//     multiWriter := io.MultiWriter(logFile, os.Stdout)
//     log.SetOutput(multiWriter)

//	    // Gin 日志也写入文件
//	    gin.DefaultWriter = multiWriter
//	}
//
// logger/logger.go
// logger/logger.go
package logger

import (
	"os"

	"go.uber.org/zap"
	"go.uber.org/zap/zapcore"
	"gopkg.in/natefinch/lumberjack.v2"
)

var SugaredLogger *zap.SugaredLogger

func SetupLogger() {
	// 从配置或环境变量读取日志级别
	var level zapcore.Level
	if err := level.Set(os.Getenv("LOG_LEVEL")); err != nil {
		// level = zapcore.InfoLevel // 默认 info
		level = zap.DebugLevel
	}

	// 配置日志编码器
	encoderConfig := zap.NewProductionEncoderConfig()
	encoderConfig.TimeKey = "timestamp"
	encoderConfig.EncodeTime = zapcore.ISO8601TimeEncoder

	// 创建写入器
	fileWriter := zapcore.AddSync(&lumberjack.Logger{
		Filename:   "./logs/diting.log",
		MaxSize:    10, // MB
		MaxBackups: 5,
		MaxAge:     30, // days
	})
	consoleWriter := zapcore.AddSync(os.Stdout)

	// 创建多个核心（文件 + 终端）
	core := zapcore.NewTee(
		zapcore.NewCore(zapcore.NewJSONEncoder(encoderConfig), fileWriter, level),
		zapcore.NewCore(zapcore.NewConsoleEncoder(encoderConfig), consoleWriter, level),
	)

	// 创建 logger
	logger := zap.New(core, zap.AddCaller())
	SugaredLogger = logger.Sugar()
	zap.ReplaceGlobals(logger)

	SugaredLogger.Info("🚀 日志系统已启动")
}
